package com.cq.hd.merchant.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FeieUtil {

    public static final String URL = "http://api.feieyun.cn/Api/Open/";//不需要修改

    public static final String USER = "huodongtongg@163.com";//*必填*：账号名
    public static final String UKEY = "QDBF7k53GFf7SBMP";//*必填*: 飞鹅云后台注册账号后生成的UKEY 【备注：这不是填打印机的KEY】
    public static final String SN = "570210334";//*必填*：打印机编号，必须要在管理后台里添加打印机或调用API接口添加之后，才能调用API

    private final static int MAX_WIDTH = 320;
    private final static int MAX_HEIGHT = 240;
    private final static int FONT_SIZE = 24;

    public static String printLabel(String customer, String enterprise) {
        String text = null;
        if (enterprise.length() > 20) {
            text = formatText2(customer, enterprise);
        } else {
            text = formatText(customer, enterprise);
        }
        return printLabelMsg(text);
    }

    public static String printLabelMsg(String content) {
        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user",USER));
        String STIME = String.valueOf(System.currentTimeMillis()/1000);
        nvps.add(new BasicNameValuePair("stime",STIME));
        nvps.add(new BasicNameValuePair("sig",signature(STIME)));
        nvps.add(new BasicNameValuePair("apiname","Open_printLabelMsg"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn", SN));
        nvps.add(new BasicNameValuePair("content",content));
        nvps.add(new BasicNameValuePair("times","1"));//打印联数

        CloseableHttpResponse response = null;
        String result = null;
        try
        {
            post.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if(statecode == 200){
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null){
                    //服务器返回的JSON字符串，建议要当做日志记录起来
                    result = EntityUtils.toString(httpentity);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally{
            try {
                if(response!=null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    //生成签名字符串
    private static String signature(String stime){
        return DigestUtils.sha1Hex(FeieUtil.USER + FeieUtil.UKEY + stime);
    }

    public static String formatText(String customer, String enterprise) {
        StringBuilder labels = new StringBuilder();

        // customer label
        int customerLabelStartY = 35;
        int customerFontRate = 2;
        int customerLabelStartX = calculateStartX(customer, FONT_SIZE * customerFontRate);
        String customerLabel = String.format("<TEXT x=\"%d\" y=\"%d\" font=\"12\" w=\"2\" h=\"2\" r=\"0\">%s</TEXT>",
                customerLabelStartX, customerLabelStartY, customer);
        labels.append(customerLabel);

        int enterpriseLabelStartY = 110;
        int charsPerLine = 10; // 每行汉字数
        String[] lines = enterprise.split("(?<=\\G.{" + charsPerLine + "})");
        for (String line : lines) {
            int startX = calculateStartX(line, FONT_SIZE);
            labels.append(
                    String.format("<TEXT x=\"%d\" y=\"%d\" font=\"12\" w=\"1\" h=\"2\" r=\"0\">%s</TEXT>",
                            startX, enterpriseLabelStartY, line)
            );
            enterpriseLabelStartY += FONT_SIZE * 2 + 2;
        }

        return labels.toString();
    }

    public static String formatText2(String customer, String enterprise) {
        StringBuilder labels = new StringBuilder();

        // customer label
        int customerLabelStartY = 60;
        int customerFontRate = 2;
        int customerLabelStartX = calculateStartX(customer, FONT_SIZE * customerFontRate);
        String customerLabel = String.format("<TEXT x=\"%d\" y=\"%d\" font=\"12\" w=\"2\" h=\"2\" r=\"0\">%s</TEXT>",
                customerLabelStartX, customerLabelStartY, customer);
        labels.append(customerLabel);

        int enterpriseLabelStartY = 135;
        int charsPerLine = 10; // 每行汉字数
        String[] lines = enterprise.split("(?<=\\G.{" + charsPerLine + "})");
        for (String line : lines) {
            int startX = calculateStartX(line, FONT_SIZE);
            labels.append(
                    String.format("<TEXT x=\"%d\" y=\"%d\" font=\"12\" w=\"1\" h=\"1\" r=\"0\">%s</TEXT>",
                            startX, enterpriseLabelStartY, line)
            );
            enterpriseLabelStartY += FONT_SIZE + 2;
        }

        return labels.toString();
    }

    private static int calculateStartX(String text, int fontSize) {
        int chineseCount = countChineseCharacters(text);
        int otherCount = text.length() - chineseCount;
        // 计算一行文本的宽度
        int textWidth = fontSize * chineseCount + fontSize / 2 * otherCount;
        return (MAX_WIDTH - textWidth) / 2;
    }

    public static int countChineseCharacters(String str) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (isChineseCharacter(c)) {
                count++;
            }
        }
        return count;
    }

    public static boolean isChineseCharacter(char c) {
        // 使用Unicode范围匹配中文字符
        return (c >= 0x4E00 && c <= 0x9FA5) || (c >= 0xFF08 && c <= 0xFF09);
    }

}
